﻿namespace System {

    /// <summary>
    /// 基础对象
    /// </summary>
    public interface IObject {

        public delegate void DisposingDelegate();

        event DisposingDelegate Disposing;

        bool IsDisposed { get; }
    }

    public abstract class KHBD_Object : IObject, IDisposable {

        public event IObject.DisposingDelegate Disposing;

        protected void AssertDispose() {
            if (IsDisposed || IsDisposing) {
                UnityEngine.Debug.LogError($"正在使用已经回收的对象 ({nameof(IsDisposed)}={IsDisposed},{nameof(IsDisposing)}={IsDisposing},{nameof(Type)}={GetType().FullName})");
                throw new NullReferenceException();
            }
        }

        protected bool IsDisposing { get; private set; }

        public bool IsDisposed { get; private set; }

        protected abstract void Dispose();

        private void DoDispose() {
            if (!IsDisposed) {
                if (Disposing != null) {
                    Disposing.Invoke();
                    Disposing = null;
                }
                IsDisposing = true;
                Dispose();
                IsDisposed = true;
                IsDisposing = false;
            }
        }

        void IDisposable.Dispose() {
            DoDispose();
        }
    }
}